package com.msy.mai.launch.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.msy.mai.common.core.constants.MessageConst;
import com.msy.mai.common.core.constants.UserConstants;
import com.msy.mai.common.core.entity.domain.R;
import com.msy.mai.common.core.utils.StringUtils;
import com.msy.mai.framework.json.core.utils.JsonUtils;
import com.msy.mai.launch.web.entity.model.LoginBody;
import com.msy.mai.launch.web.entity.model.RegisterBody;
import com.msy.mai.launch.web.service.SysRegisterService;
import com.msy.mai.launch.web.strategy.factory.TokenGranterFactory;
import com.msy.mai.launch.web.entity.vo.UserLoginVO;
import com.msy.mai.module.system.entity.vo.SysClientVo;
import com.msy.mai.module.system.service.SysClientService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Wang
 * @version 1.0
 * @Date 2024/10/27 下午2:19
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "default - 认证模块")
@SaIgnore
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final TokenGranterFactory tokenGranterFactory;

    private final SysClientService sysClientService;

    private final SysRegisterService sysRegisterService;

    @PostMapping("/login")
    @Operation(summary = "统一登录接口")
    public R<UserLoginVO> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();

        SysClientVo clientVo = sysClientService.queryClientVOById(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(clientVo) || !StringUtils.contains(clientVo.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageConst.AUTH_POLICY_TYPE_NOT_EXIST);
        }
        // 认证client不可用
        if (!UserConstants.NORMAL.equals(clientVo.getStatus())) {
            return R.fail(MessageConst.AUTH_POLICY_TYPE_BLOCKED);
        }

        return R.ok(tokenGranterFactory.getStrategy(grantType).login(body,clientVo));
    }

    @PostMapping("register")
    @Operation(summary = "密码注册接口")
    public R<?> register(@RequestBody @Validated RegisterBody registerBody) {
        sysRegisterService.register(registerBody);
        return R.ok();
    }


}
